<template>
  <!--试卷-->
  <div class="paper" >
    <!--过滤器-->
    <div class="filter-container">
      <div class="filter-item item-input">
        <el-input v-model="paperInput" placeholder="请输入试卷名称"></el-input>
      </div>
      <div class="filter-item item-button">
        <el-button type="primary" @click="searchPaper"><i class="el-icon-search"></i> 搜索</el-button>
      </div>
      <div class="filter-item item-button">
        <el-button type="primary" @click="refreshPaper"><i class="el-icon-refresh"></i> 刷新</el-button>
      </div>
      <div class="filter-item item-button">
        <el-button type="primary" @click="toCreatePaper = true"><i class="el-icon-s-flag"></i> 创建试卷</el-button>
      </div>
    </div>

    <!--试卷列表，分页处理-->
    <div class="paper-list" v-if="paperDetail.length == 0">
      <el-table border style="width: 100%">
        <el-table-column label="序号" width="70" align="center"></el-table-column>
        <el-table-column label="试卷名称" align="center"></el-table-column>
        <el-table-column label="创建时间" width="280" align="center"></el-table-column>
        <el-table-column label="出卷人" width="280" align="center"></el-table-column>
        <el-table-column label="状态" width="100" align="center"></el-table-column>
        <el-table-column label="操作" width="360"></el-table-column>
      </el-table>
    </div>
    <div class="paper-list" v-if="paperDetail.length > 0">
      <el-table
          :data="paperDetail.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
          border
          style="width: 100%">
        <el-table-column
            label="序号"
            width="70"
            align="center">
          <template slot-scope="scope" v-if="paperDetail.length > 0 ">
            {{scope.$index + 1}}
          </template>
        </el-table-column>
        <el-table-column
            prop="name"
            label="试卷名称"
            width="320"
            align="center">
          <template slot-scope="scope">
            <span class="col2-cell-style" @click="requestPaperDetail(paperDetail[(currentPage - 1) * pageSize + scope.$index].id),viewPaper((currentPage - 1) * pageSize + scope.$index)">{{scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="createdTime"
            label="创建时间"
            width="280"
            align="center">
        </el-table-column>
        <el-table-column
            prop="creator"
            label="出卷人"
            width="120"
            align="center">
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            width="110"
            align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 0" type="warning" disable-transitions>空白卷</el-tag>
            <el-tooltip content="已选题目但未确定是否使用该试卷" placement="top">
              <el-tag v-if="scope.row.status == 1" type="info" disable-transitions>未确定</el-tag>
            </el-tooltip>
            <el-tag v-if="scope.row.status == 2" type="success" disable-transitions>使用中</el-tag>
            <el-tag v-if="scope.row.status == 3" type="danger" disable-transitions>已禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="360">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="danger"
                @click="curPaperIndex = (currentPage - 1) * pageSize + scope.$index, toDelPaper = true">删除
            </el-button>
            <el-button
                size="mini"
                type="primary"
                v-if="scope.row.status < 2"
                @click="locateCurPaper((currentPage - 1) * pageSize + scope.$index)">添加题目
            </el-button>
            <el-button
                size="mini"
                type="success"
                v-if="scope.row.status < 2"
                @click="usePaper((currentPage - 1) * pageSize + scope.$index)">使用试卷
            </el-button>
            <el-button
                size="mini"
                type="info"
                v-if="scope.row.status === 2"
                @click="preDisablePaper((currentPage - 1) * pageSize + scope.$index)">禁用
            </el-button>
            <el-button
                size="mini"
                v-if="scope.row.status === 3"
                @click="preEnablePaper((currentPage - 1) * pageSize + scope.$index)">启用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--分页-->
    <Pagination :currentPage="currentPage" :pageSize="pageSize" :total="paperDetail.length"
                :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"></Pagination>
    <!--<div class="pagination-container">-->
    <!--<el-pagination-->
    <!--@size-change="handleSizeChange"-->
    <!--@current-change="handleCurrentChange"-->
    <!--:current-page="currentPage"-->
    <!--:page-sizes="[10, 20, 30, 50]"-->
    <!--:page-size="pageSize"-->
    <!--layout="total, sizes, prev, pager, next, jumper"-->
    <!--:total="paperDetail.length">-->
    <!--</el-pagination>-->
    <!--</div>-->

    <!--创建试卷-->
    <el-dialog title="创建试卷" :visible.sync="toCreatePaper" top="2vh">
      <el-form ref="paperForm" :model="paperForm" status-icon :rules="paperRules">
        <el-form-item label="试卷名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="paperForm.name" autocomplete="off" placeholder="请输入试卷名称"></el-input>
        </el-form-item>
        <el-form-item label="出卷人" :label-width="formLabelWidth" prop="creator">
          <el-input v-model="paperForm.creator" autocomplete="off" placeholder="请输入出卷人名字"></el-input>
        </el-form-item>
        <el-form-item label="题目数量" :label-width="formLabelWidth" prop="questSum">
          <el-input-number v-model="paperForm.questSum" @change="handleNumChange" :min="1" :max="20"
                           label="题目数量"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toCreatePaper = false">取 消</el-button>
        <el-button type="primary" @click="createPaper()">确 定</el-button>
      </div>
    </el-dialog>

    <!--添加题目-->
    <el-dialog title="添加题目" :visible.sync="toAddQuestion" top="1vh" width="80%">
      <div slot="title" class="header-title">
        <span>添加题目：{{ paperTitle }}</span>
      </div>

      <!--添加题目 过滤栏-->
      <div class="filter-bar" v-if="paperDetail.length != 0">
        <el-select v-model="categValue" placeholder="请输入" class="filter-item" filterable
                   @change="problemTypeSearch">
          <el-option
              v-for="item in categOptions"
              :key="item.value"
              :label="item.label"
              :value="item.label"
          >
          </el-option>
        </el-select>
        <el-input
            @change="searchIsEmpty"
            placeholder="请输入关键词"
            v-model="questKeyInput"
            clearable
            class="filter-item">
        </el-input>
        <el-button type="primary" class="filter-item" @click="searchProblem"><i class="el-icon-search"></i> 搜索
        </el-button>
        <el-button type="primary" class="filter-item" @click="refreshProblem"><i class="el-icon-refresh"></i> 刷新</el-button>
        <el-progress type="circle" class="filter-item"
                     :percentage="paperDetail[curPaperIndex].questions.length / paperDetail[curPaperIndex].questSum * 100"
                     :width="60" color="#67C23A" :show-text="false"></el-progress>
        <span class="filter-item">{{paperDetail[curPaperIndex].questions.length}} / {{paperDetail[curPaperIndex].questSum}}</span>
      </div>

      <!--题目表格-->
      <el-table
          :data="showLib.slice((questCurPage - 1) * questPageSize, questCurPage * questPageSize)"
          style="width: 100%"
          v-if="paperDetail.length != 0">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <div label-position="left" inline class="question-table-expand">
              <h4>【题目描述】</h4>
              <p v-html="scope.row.detail.description"></p>
              <h4>【输入格式】</h4>
              <p v-html="scope.row.detail.input"></p>
              <h4>【输出格式】</h4>
              <p v-html="scope.row.detail.output"></p>
              <h4>【输入样例】</h4>
              <p v-html="scope.row.detail.inputSample"></p>
              <h4>【输出样例】</h4>
              <p v-html="scope.row.detail.outputSample"></p>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            label="#"
            width="60"
            prop="id"
            align="center">
          <!--                    <template slot-scope="scope">-->
          <!--                        {{scope.$index + 1}}-->
          <!--                    </template>-->
        </el-table-column>
        <el-table-column
            label="题目"
            prop="name"
            align="center"
            width="300">
        </el-table-column>
        <el-table-column
            label="类型"
            prop="type"
            align="center"
            width="300">
        </el-table-column>
        <el-table-column
            label="难度"
            prop="difficulty"
            align="center"
            width="160">
        </el-table-column>
        <el-table-column
            label="来源"
            prop="source"
            align="center">
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="success"
                v-if="isAdd((questCurPage - 1) * questPageSize + scope.$index) == false"
                @click="addQuestion((questCurPage - 1) * questPageSize + scope.$index)">添加
            </el-button>
            <el-button
                size="mini"
                type="danger"
                v-if="isAdd((questCurPage - 1) * questPageSize + scope.$index) == true"
                @click="deleteQuestion((questCurPage - 1) * questPageSize + scope.$index)">删除
            </el-button>
            <el-button
                size="mini"
                type="warning"
                @click="viewProblemDetail((questCurPage - 1) * questPageSize + scope.$index)">查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <Pagination :currentPage="questCurPage" :pageSize="questPageSize"
                  :total="showLib.length" :handleSizeChange="handleSizeChange2"
                  :handleCurrentChange="handleCurrentChange2"></Pagination>
    </el-dialog>

    <!--查看题目详情 对话框-->
    <el-dialog title="查看题目详情" :visible.sync="toViewProblemDetail" top="2vh" width="60%">
      <div slot="title" class="header-title">
        <span></span>
      </div>

      <!--题目详情-->
      <div class="problem-detail" v-if="showLib[curProblemIndex]">
        <div class="problem-header">
          <span class="problem-name">查看题目详情：{{showLib[curProblemIndex].name}}</span>
        </div>
        <div class="problem-body">
          <section>
            <h4>描述</h4>
            <div class="description">
              <p v-html="showLib[curProblemIndex].detail.description"></p>
            </div>
          </section>
          <section class="border-top-style">
            <h4>格式</h4>
            <h5>输入格式</h5>
            <div class="description">
              <p v-html="showLib[curProblemIndex].detail.input"></p>
            </div>
            <h5>输出格式</h5>
            <div class="description">
              <p v-html="showLib[curProblemIndex].detail.output"></p>
            </div>
          </section>
          <section class="border-top-style sample">
            <h4>样例</h4>
            <h5>输入样例</h5>
            <div class="description">
              <pre v-html="showLib[curProblemIndex].detail.inputSample"></pre>
            </div>
            <h5>输出样例</h5>
            <div class="description">
              <pre v-html="showLib[curProblemIndex].detail.outputSample"></pre>
            </div>
          </section>
          <section class="border-top-style">
            <h4>限制</h4>
            <div class="description">
              <p><strong>时间限制：</strong>{{showLib[curProblemIndex].detail.timeLimit}} ms</p>
              <p><strong>内存限制：</strong>{{showLib[curProblemIndex].detail.memoryLimit}} KB</p>
            </div>
          </section>
          <section class="border-top-style"
                   v-if="showLib[curProblemIndex].detail.hint != null && showLib[curProblemIndex].detail.hint.trim().length !== 0">
            <h4>提示</h4>
            <div class="description">
              <p v-html="showLib[curProblemIndex].detail.hint"></p>
            </div>
          </section>
          <section class="border-top-style">
            <h4>测试集</h4>
            <div class="description">
              <div class="sample checkpoints" v-for="(item, index) in curCheckpoints"
                   :class="index == 0 ? 'first-checkpoint' : ''">
                <h5>测试点 {{index + 1}}</h5>
                <h6>输入</h6>
                <pre>{{item.checkpoint_input}}</pre>
                <h6>输出</h6>
                <pre>{{item.checkpoint_output}}</pre>
              </div>
            </div>
          </section>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="toViewProblemDetail = false">关闭</el-button>
      </div>
    </el-dialog>

    <!--查看试卷 对话框-->
    <el-dialog title="查看试卷" :visible.sync="toViewPaper" top="2vh" width="80%" v-if="paperDetail.length != 0">
      <div class="paper-container">
        <div class="paper-header">
          <!--                    <h1>湘潭大学_____年计算机专业上机考试</h1>-->
          <h1>{{paperTitle}}</h1>
        </div>

        <div class="paper-info">
          <h3>考试总分：{{paperDetail[curPaperIndex].questSum * 100}}</h3>
          <h3>出卷人：{{paperDetail[curPaperIndex].creator}}</h3>
        </div>

        <!--试卷内容-->
        <div class="paper-content" v-for="(item, index) in paperDetail[curPaperIndex].questions" :key="index">
          <h2>第 {{index + 1}} 题&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{lib[item].name}}</h2>
          <h4>【问题描述】</h4>
          <p v-html="lib[item].detail.description"></p>
          <h4>【输入格式】</h4>
          <p v-html="lib[item].detail.input"></p>
          <h4>【输出格式】</h4>
          <p v-html="lib[item].detail.output"></p>
          <h4>【输入样例】</h4>
          <p v-html="lib[item].detail.inputSample"></p>
          <h4>【输出样例】</h4>
          <p v-html="lib[item].detail.outputSample"></p>
        </div>
      </div>
    </el-dialog>

    <!--删除试卷 对话框-->
    <el-dialog title="" :visible.sync="toDelPaper" top="18vh" width="33%" center :show-close="false">
      <div class="delete-header">
        <div class="header-icon">
          <span class="icon-text">!</span>
        </div>
      </div>
      <div class="delete-tip">是否删除该试卷？如若试卷正在使用，则无法删除</div>
      <div slot="footer">
        <el-button type="primary" @click="deletePaper(curPaperIndex)">确定删除</el-button>
        <el-button type="info" @click="toDelPaper = false">取消</el-button>
      </div>
    </el-dialog>

    <!--启用班级 对话框-->
    <el-dialog title="" :visible.sync="toEnablePaper" top="18vh" width="33%" center :show-close="false">
      <div class="delete-header">
        <div class="header-icon">
          <span class="icon-text">!</span>
        </div>
      </div>
      <div class="delete-tip">是否启用该试卷？确定启用后该试卷可用于组考</div>
      <div slot="footer">
        <el-button type="primary" @click="enablePaper(curPaperIndex)">确定启用</el-button>
        <el-button type="info" @click="toEnablePaper = false">取消</el-button>
      </div>
    </el-dialog>

    <!--禁用班级 对话框-->
    <el-dialog title="" :visible.sync="toDisablePaper" top="18vh" width="33%" center :show-close="false">
      <div class="delete-header">
        <div class="header-icon">
          <span class="icon-text">!</span>
        </div>
      </div>
      <div class="delete-tip">是否禁用该试卷？确定禁用后该试卷将无法用于组考</div>
      <div slot="footer">
        <el-button type="primary" @click="disablePaper(curPaperIndex)">确定禁用</el-button>
        <el-button type="info" @click="toDisablePaper = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '../Pagination';
import Axios from 'axios';

export default {
  // name: "",
  data() {
    return {
      paperInput: '', // 试卷搜索框的值
      questKeyInput: '', // 输入框的题目关键词
      showLib: [],
      lib: [],//题库
      paperDetail: [],
      currentPage: 1,
      pageSize: 20,
      questCurPage: 1, // 题库当前页码
      questPageSize: 20, // 题库每页条目个数
      curProblemIndex: 0,
      curCheckpoints: [],
      toViewProblemDetail: false,
      toCreatePaper: false,
      toDelPaper: false,
      toEnablePaper: false,
      toDisablePaper: false,
      toAddQuestion: false,
      paperForm: {
        name: '',
        creator: '',
        questSum: 1
      },
      formLabelWidth: '100px',
      paperRules: {
        name: [
          {required: true, message: '请输入试题名称', trigger: 'blur'},
          {min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur'}
        ],
        creator: [
          {required: true, message: '请输入出卷人名字', trigger: 'blur'},
          {min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur'}
        ],
        questSum: [
          {required: true, message: '试题数量不能为空', trigger: 'blur'},
          {type: 'number', message: '试题数量必须为数字值', trigger: 'blur'}
        ]
      },
      categOptions: [],
      categValue: '请选择题目类型',
      toViewPaper: false,
      curPaperIndex: 0,
      paperTitle: ''
    }
  },
  components: {
    Pagination
  },
  mounted() {
    if (localStorage.getItem("token") != null) {
      this.requestPaper();
      this.requestProblem();
      this.requestProblemType();
    } else {
      this.$router.push( { path: "/login" });
    }
    //MathJax
    // this.$nextTick(function () {
    //     //这里要注意，使用$nextTick等组件数据渲染完之后再调用MathJax渲染方法，要不然会获取不到数据
    //     //判断是否初始配置，若无则配置。
    //     if(this.commonsVariable.isMathjaxConfig){
    //         this.commonsVariable.initMathjaxConfig();
    //     }
    //     //传入组件id，让组件被MathJax渲染
    //     this.commonsVariable.MathQueue("problem-detail-description");
    // })
  },
  methods: {
    requestProblem() {
      let qLib = [];   // 题库
      Axios({
        method: 'post',
        url: '/admin/getProblemLib',
        data: {
          adminToken:localStorage.getItem("adminToken"),
        },
        transformRequest: [
          function (data) {
            let ret = ''
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3){
          this.$router.push( { path: "/login" })
          return;
        }
        this.questCurPage = 1;
        for (let i = 0; i < res.data.length; i++) {
          let Lib = {};
          Lib.id = res.data[i].problem_id;
          Lib.name = res.data[i].problem_name;
          Lib.type = res.data[i].problem_category_name;
          Lib.stem = res.data[i].problem_description;
          Lib.source = '本校题库';
          Lib.difficulty = res.data[i].problem_tag_name;
          Lib.isAdded = false;

          let detail = {};
          detail.description = res.data[i].problem_description;
          detail.input = res.data[i].problem_input_format;
          detail.output = res.data[i].problem_output_format;
          detail.inputSample = res.data[i].problem_sample_input;
          detail.outputSample = res.data[i].problem_sample_output;
          detail.timeLimit = res.data[i].problem_time_limit;
          detail.memoryLimit = res.data[i].problem_memory_limit;
          detail.hint = res.data[i].problem_hint;
          //处理换行
          detail.inputSample = detail.inputSample.replace(/\n/g, "<br>");
          detail.outputSample = detail.outputSample.replace(/\n/g, "<br>");
          detail.output = detail.output.replace(/\n/g, "<br>");
          detail.input = detail.input.replace(/\n/g, "<br>");
          detail.description = detail.description.replace(/\n/g, "<br>");
          detail.outputSample = detail.outputSample.replace(new RegExp(/( )/g), "&nbsp;&nbsp;&nbsp;");
          //处理图片
          let temp = detail.description;
          let picIndex = temp.indexOf('[1]:');
          if (picIndex != -1) {
            let picAddress = [];
            picAddress = temp.substring(picIndex).replace('<br>', ',').replace(new RegExp(/( )/g), "").split(',');
            for (let i = 0; i < picAddress.length; i++) {
              picAddress[i] = "<img src='" + picAddress[i].substring(4) + "'>";
            }
            detail.description = detail.description.substring(0, picIndex);
            for (let i = 0; i < picAddress.length; i++) {
              let pic = detail.description.indexOf('![enter image description here]');
              let head = detail.description.substring(0, pic);
              let tail = detail.description.substring(pic + 34, detail.description.length);
              detail.description = head + picAddress[i] + tail;
            }
          }
          Lib.detail = detail;
          qLib.push(Lib);
        }
      }).catch((err) => {
        console.log(err);
      })


      this.lib = qLib;
      this.showLib = qLib;
    },
    requestProblemType() {
      Axios({
        method: 'post',
        url: '/admin/getProblemType',
        data: {
          adminToken:localStorage.getItem("adminToken"),
        },
        transformRequest: [
          function (data) {
            let ret = ''
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3){
          this.$router.push( { path: "/login" })
          return;
        }
        this.categOptions = [];
        let firstOption = {};
        firstOption.value = '选项0';
        firstOption.label = '请选择题目类型';
        this.categOptions.push(firstOption);
        for (let i = 0; i < res.data.length; i++) {
          let tempOption = {};
          tempOption.value = '选项' + (i + 1);
          tempOption.label = res.data[i].problem_category_name;
          this.categOptions.push(tempOption);
        }
      }).catch((err) => {
        console.log(err);
      })

    },
    requestPaper() {
      this.paperDetail = [];
      Axios({
        method: 'post',
        url: '/admin/getPaperDetail',
        data: {
          adminToken:localStorage.getItem("adminToken"),
          adminName:localStorage.getItem("adminName"),
        },
        transformRequest: [
          function (data) {
            let ret = ''
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3){
          this.$router.push( { path: "/login" })
          return;
        }
        this.currentPage = 1;
        for (let i = res.data.length - 1 ; i >= 0; i--) {
          let paper = {};
          paper.id = res.data[i].paper_id;
          paper.name = res.data[i].paper_title;
          paper.createdTime = this.getTime(res.data[i].paper_create_time);
          paper.creator = res.data[i].paper_creator;
          paper.status = res.data[i].paper_status;
          paper.questSum = res.data[i].paper_quest_sum;
          paper.questions = [];

          this.paperDetail.push(paper);
        }
      }).catch((err) => {
        console.log(err);
      })
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleSizeChange2(val) {
      this.questPageSize = val;
    },
    handleCurrentChange2(val) {
      this.questCurPage = val;
    },
    handleNumChange(value) {
      console.log(value);
    },
    // 查看试卷
    viewPaper(index) {
      this.curPaperIndex = index;
      this.paperTitle = this.paperDetail[index].name;
      this.toViewPaper = true;
    },
    // 定位当前试卷，设置添加题目的试卷的当前索引
    locateCurPaper(index) {
      this.questKeyInput = '';
      this.showLib = this.lib;
      this.categValue = '请选择题目类型';
      this.curPaperIndex = index;
      this.questCurPage = 1;
      this.questPageSize = 20;
      this.paperTitle = this.paperDetail[index].name;
      this.requestPaperDetail(this.paperDetail[index].id);
      this.toAddQuestion = true;
    },
    // 删除试卷
    deletePaper(index) {
      let paperIndex;
      for (let i = 0; i < this.paperDetail.length; i++) {
        if (this.paperDetail[index].id == this.paperDetail[i].id) {
          paperIndex = i;
          break;
        }
      }

      Axios({
        method: 'post',
        url: '/admin/deletePaper',
        data: {
          adminToken:localStorage.getItem("adminToken"),
          paper_id: this.paperDetail[paperIndex].id,
          paper_title: this.paperDetail[paperIndex].name,
        },
        transformRequest: [
          function (data) {
            let ret = ''
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3){
          this.$router.push( { path: "/login" })
          return;
        }
        this.toDelPaper = false;
        // console.log(this.paperDetail[index].name)
        if(res.data == 0){
          this.$notify({
            title: '成功',
            message: this.paperDetail[index].name + ' -- 删除成功',
            type: 'success',
            duration: 3000
          });
          this.requestPaper();
        }else if(res.data == 1){
          this.$notify({
            title: '失败',
            message: '此试卷正在使用',
            type: 'error',
            duration: 3000
          });
        }
      }).catch((err) => {
        console.log(err);
      })


    },
    // 创建试卷
    createPaper() {
      let pattern = /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
      if (pattern.test(this.paperForm.name)) {
        this.$message.warning('试卷名称不能包含特殊字符')
        return;
      }
      this.$refs['paperForm'].validate((valid) => {
        if (valid) {
          this.toCreatePaper = false;
          this.$message({
            message: '试卷创建成功！',
            type: 'success',
            duration: 3000
          });

          Axios({
            method:'post',
            url:'/admin/saveNewPaper',
            data:{
              adminToken:localStorage.getItem("adminToken"),
              paper_title: this.paperForm.name,
              paper_creator: this.paperForm.creator,
              paper_quest_sum: this.paperForm.questSum,
              adminName: localStorage.getItem("adminName")
            },
            transformRequest: [
              function (data) {
                let ret = ''
                for (let it in data) {
                  ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
                ret = ret.substring(0, ret.lastIndexOf('&'));
                return ret
              }
            ],
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
          }).then((res) => {
            if (res.data == 3){
              this.$router.push( { path: "/login" })
              return;
            }
            if(res.data == 'success'){
              this.requestPaper();
            }
          }).catch((err) => {
            console.log(err);
          })

        } else {
          return false;
        }
      });
    },
    // 添加题目
    addQuestion(index) {
      this.curProblemIndex = index;
      let problem_index;
      if (this.paperDetail[this.curPaperIndex].questions.length >= this.paperDetail[this.curPaperIndex].questSum) {
        this.$notify.error({
          title: '错误',
          message: '题目已经选满！',
          duration: 3000
        });
        return;
      } else {
        let problemIndex;
        for (let i = 0; i < this.lib.length; i++) {
          if (this.showLib[index].id == this.lib[i].id) {
            problemIndex = i;
            break;
          }
        }
        problem_index = problemIndex;
        this.paperDetail[this.curPaperIndex].questions.push(problemIndex);
        this.paperDetail[this.curPaperIndex].questions.sort(function newSort(value1, value2) {
          if (value1 > value2)
            return 1;
          else if (value1 < value2)
            return -1;
          else
            return 0;
        });
      }
      if (this.paperDetail[this.curPaperIndex].questions.length > 0) {
        this.paperDetail[this.curPaperIndex].status = 1;
      }

      Axios({
        method: 'post',
        url: '/admin/insertQuestions',
        data:{
          adminToken:localStorage.getItem("adminToken"),
          paper_id: this.paperDetail[this.curPaperIndex].id,
          problem_id: this.lib[problem_index].id,
        },
        transformRequest: [
          function (data) {
            let ret = ''
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3){
          this.$router.push( { path: "/login" })
          return;
        }
        // console.log(res);
      }).catch((err) => {
        console.log(err);
      })
    },
    // 删除题目
    deleteQuestion(index) {
      this.curProblemIndex = index;
      let problem_id;
      let problemIndex ;
      for(let i = 0 ; i < this.lib.length ; i++){
        if(this.showLib[index].id == this.lib[i].id){
          problemIndex = i;
          break;
        }
      }
      let qLibIndex = this.paperDetail[this.curPaperIndex].questions.indexOf(problemIndex);
      problem_id = problemIndex;
      if (qLibIndex != -1) {
        this.paperDetail[this.curPaperIndex].questions.splice(qLibIndex, 1);
      }
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'warning',
        duration: 3000
      });
      // console.log(this.lib[problem_id].id);
      if (this.paperDetail[this.curPaperIndex].questions.length <= 0) {
        this.paperDetail[this.curPaperIndex].status = 0;
      }

      Axios({
        method: 'post',
        url: '/admin/deleteQuestions',
        data:{
          adminToken:localStorage.getItem("adminToken"),
          paper_id: this.paperDetail[this.curPaperIndex].id,
          problem_id: this.lib[problem_id].id,
        },
        transformRequest: [
          function (data) {
            let ret = ''
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3){
          this.$router.push( { path: "/login" })
          return;
        }
        // console.log(res);
      }).catch((err) => {
        console.log(err);
      })

    },
    // 查看题目详情
    viewProblemDetail(index) {
      this.curProblemIndex = index;
      this.$axios({
        method: 'post',
        url: '/admin/getCurCheckpoints',
        data: {
          pid: this.showLib[index].id,
          adminToken: localStorage.getItem("adminToken")
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        // console.log(res.data);
        this.curCheckpoints = res.data;
        this.toViewProblemDetail = true;
      }).catch((err) => {
        this.$notify({
          title: '错误',
          message: '数据获取失败',
          type: 'error',
          duration: 3000
        });
        console.log(err);
      });
    },
    // 使用试卷
    usePaper(index) {
      this.curPaperIndex = index;
      if (this.paperDetail[this.curPaperIndex].questions.length < this.paperDetail[this.curPaperIndex].questSum) {
        let num = this.paperDetail[this.curPaperIndex].questSum - this.paperDetail[this.curPaperIndex].questions.length;
        this.$notify.error({
          title: '错误',
          message: '尚有 ' + num + ' 道题目未选！',
          duration: 3000
        });
        return;
      }
      this.paperDetail[this.curPaperIndex].status = 2;

      this.$notify({
        title: '成功',
        message: '成功',
        type: 'success',
        duration: 3000
      });

      Axios({
        method: 'post',
        url: '/admin/usePaper',
        data:{
          adminToken:localStorage.getItem("adminToken"),
          paper_id: this.paperDetail[this.curPaperIndex].id,
          paper_title: this.paperDetail[this.curPaperIndex].name,
        },
        transformRequest: [
          function (data) {
            let ret = ''
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3){
          this.$router.push( { path: "/login" })
          return;
        }
        // console.log(res);
      }).catch((err) => {
        console.log(err);
      })
    },
    // 启用试卷预处理
    preEnablePaper(index) {
      this.curPaperIndex = index;
      this.toEnablePaper = true;
    },
    // 禁用班级预处理
    preDisablePaper(index) {
      this.curPaperIndex = index;
      this.toDisablePaper = true;
    },
    // 启用试卷
    enablePaper(index) {
      Axios({
        method: 'post',
        url: '/admin/enablePaper',
        data: {
          paper_id: this.paperDetail[index].id,
          adminToken: localStorage.getItem("adminToken"),
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        // console.log(res.data);
        this.toEnablePaper = false;
        this.$notify({
          title: this.paperDetail[index].name,
          message: '启用成功',
          type: 'success',
          duration: 3000
        });
        this.paperDetail[index].status = 2;
      }).catch((err) => {
        console.log(err);
      });
    },
    // 禁用试卷
    disablePaper(index) {
      Axios({
        method: 'post',
        url: '/admin/disablePaper',
        data: {
          paper_id: this.paperDetail[index].id,
          adminToken: localStorage.getItem("adminToken"),
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        // console.log(res.data);
        this.toDisablePaper = false;
        this.$notify({
          title: this.paperDetail[index].name,
          message: '禁用成功',
          type: 'success',
          duration: 3000
        });
        this.paperDetail[index].status = 3;
      }).catch((err) => {
        console.log(err);
      });
    },
    //题目标题搜索
    searchProblem() {
      this.questCurPage = 1;
      if (this.questKeyInput == '') {
        this.showLib = this.lib;
        this.$message.warning('查询条件不能为空');
        return;
      }
      this.showLib = [];
      this.lib.forEach((value, index) => {
        if (value.name) {
          if (value.name.indexOf(this.questKeyInput) >= 0) {
            this.showLib.push(value);
          }
        }
      });
    },
    searchIsEmpty() {
      this.questCurPage = 1;
      if (this.questKeyInput == '') {
        this.showLib = this.lib;
      }
    },
    //题目类型搜索
    problemTypeSearch(option) {
      this.questCurPage = 1;
      if (this.categValue == '请选择题目类型') {
        this.showLib = this.lib;
        return;
      }
      this.showLib = [];
      this.lib.forEach((value, index) => {
        if (value.type) {
          if (value.type.indexOf(option) >= 0) {
            this.showLib.push(value);
          }
        }
      });
    },
    //判断题目是否被添加
    isAdd(index) {
      let problemIndex;
      if (this.showLib.length != this.lib.length)
      {
        for (let i = 0; i < this.lib.length; i++) {
          if (this.showLib[index].id == this.lib[i].id) {
            problemIndex = i;
            break;
          }
        }
      }else{
        problemIndex = index;
      }
      if (this.paperDetail[this.curPaperIndex].questions.indexOf(problemIndex) == -1){
        return false;
      }
      else{
        return true;
      }
    },
    //试卷名称搜索
    searchPaper() {
      if (this.paperInput == '') {
        this.requestPaper();
        this.$message.warning('查询条件不能为空');
        return;
      }
      Axios({
        method: 'post',
        url: '/admin/searchPaperByTitle',
        data:{
          adminToken:localStorage.getItem("adminToken"),
          adminName:localStorage.getItem("adminName"),
          paper_title: this.paperInput,
        },
        transformRequest: [
          function (data) {
            let ret = ''
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3){
          this.$router.push( { path: "/login" })
          return;
        }
        this.currentPage = 1;
        this.paperDetail = [];
        // console.log(res);
        if(res){
          for (let i = res.data.length - 1 ; i >= 0; i--) {
            let paper = {};
            paper.id = res.data[i].paper_id;
            paper.name = res.data[i].paper_title;
            paper.createdTime = this.getTime(res.data[i].paper_create_time);
            paper.creator = res.data[i].paper_creator;
            paper.status = res.data[i].paper_status;
            paper.questSum = res.data[i].paper_quest_sum;
            paper.questions = res.data[i].paper_questions;
            if(paper.questions){
              if(paper.questions.length > 1){
                if(paper.questions.indexOf(",") != -1){
                  paper.questions = res.data[i].paper_questions.split(",");
                  for (let j = 0; j < paper.questions.length; j++) {
                    paper.questions[j] = parseInt(paper.questions[j]);
                  }
                }
              }
            }else{
              paper.questions = [];
            }
            this.paperDetail.push(paper);
          }
        }
      }).catch((err) => {
        console.log(err);
      })
    },
    refreshPaper(){
      this.paperInput = '';
      this.requestPaper();
    },
    refreshProblem(){
      this.questKeyInput = '';
      this.categValue = '请选择题目类型';
      this.requestProblem();
    },
    requestPaperDetail(id){
      Axios({
        method: 'post',
        url: '/admin/getProblemByPaper',
        data: {
          adminToken:localStorage.getItem("adminToken"),
          paper_id: id,
        },
        transformRequest: [
          function (data) {
            let ret = ''
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((response) => {
        if (response.data == 3){
          this.$router.push( { path: "/login" })
          return;
        }
        // console.log(response)
        if(response.data.length){
          let paperId;
          for(let y = 0 ; y < this.paperDetail.length ; y++){
            if(this.paperDetail[y].id == id)
              paperId = y;
          }
          this.paperDetail[paperId].questions = [];
          for(let l = 0 ; l < response.data.length; l++){
            let problemIndex;
            for(let x = 0 ; x < this.lib.length ; x++) {
              if (this.lib[x].id == response.data[l]) {
                problemIndex = x;
                break;
              }
            }
            // let paper;
            // paper.questions.push(problemIndex);
            this.paperDetail[paperId].questions.push(problemIndex);
          }
        }
      }).catch((error) => {
        console.log(error);
      })
    }
  }
}
</script>

<style scoped>
.paper {
  width: 100%;
}

.filter-container {
  padding-bottom: 10px;
}

.filter-item {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
}

.item-input {
  width: 200px;
  margin-right: 5px;
}

.filter-container .filter-item:nth-child(3), .filter-container .filter-item:nth-child(4) {
  margin-left: 16px;
}

.paper-list {
  width: 100%;
}

.filter-bar {
  width: 100%;
  padding-bottom: 10px;
}

.filter-bar .el-select, .filter-bar .el-input {
  width: 20%;
  margin-right: 20px;
}

.filter-bar .el-progress {
  margin-left: 20px;
}

.filter-bar span {
  margin-left: 10px;
}

.question-table-expand {
  padding: 0 50px;
}

.paper-list .col2-cell-style {
  color: #409EFF;
  cursor: pointer;
}

.el-dialog .paper-container {
  margin: 0 20px;
}

.el-dialog .paper-container .paper-header h1 {
  text-align: center;
  font-size: 2.5em;
}

.el-dialog .paper-container .paper-info {
  text-align: center;
  padding: 20px;
}

.el-dialog .paper-container .paper-info h3 {
  display: inline-block;
  width: 25%;
}

.paper-container .paper-content {
  padding: 20px;
}

.problem-detail .problem-header {
  background-color: #16a085;
  color: #fff;
  padding: 10px;
}

.problem-body {
  padding: 20px;
  background-color: white;
}

.problem-body .border-top-style, .checkpoints {
  border-top: 5px solid #16a085;
  padding-top: 10px;
  margin-top: 30px;
}

.problem-body .border-top-style .description .first-checkpoint {
  border-top-width: 0;
  padding-top: 0;
  margin-top: 0;
}

.problem-body .sample {
  border-top-color: #ff7373;
}

.problem-body .description, .checkpoints-body .description {
  color: #666;
  margin-left: 20px;
}

.problem-detail h4 {
  font-size: 18px;
  margin-top: 4px;
}

.problem-detail h5 {
  font-size: 17px;
}

.problem-detail h6 {
  font-size: 16px;
}

.problem-detail h4, .problem-detail h5, .problem-detail h6 {
  font-weight: 500;
  margin: 10px 0;
  text-transform: uppercase;
}

.problem-detail p {
  margin-bottom: 10px;
}

.problem-detail .sample pre {
  display: block;
  padding: 10px;
  margin: 0 0 10px;
  font-size: 13px;
  line-height: 20px;
  word-break: break-all;
  word-wrap: break-word;
  white-space: pre-wrap;
  background-color: #f5f5f5;
  border: 1px solid rgba(0, 0, 0, 0.15);
  border-radius: 4px;
}

</style>
